package ucuserslogic

import (
	"context"
	"fmt"
	"go.uber.org/zap"
	"navi-mumbai/app/rpc/usercenter/internal/svc"
	"navi-mumbai/app/rpc/usercenter/pb"
	"navi-mumbai/common/auth"
	"navi-mumbai/common/ctxdata"
	"navi-mumbai/common/xerr"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type GenerateTokenLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGenerateTokenLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GenerateTokenLogic {
	return &GenerateTokenLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 生成JWT token
func (l *GenerateTokenLogic) GenerateToken(in *pb.GenerateTokenReq) (*pb.GenerateTokenResp, error) {
	now := time.Now().Unix()
	accessExpire := l.svcCtx.Config.JwtAuth.AccessExpire
	accessToken, err := l.getJwtToken(l.svcCtx.Config.JwtAuth.AccessSecret, now, accessExpire, in.Uid, in.UserChannel, in.AppVer, in.AuthKey, in.AuthType)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.RequestParamError, fmt.Sprintf("getJwtToken err userId:%d , err:%v", in.Uid, err))
	}

	return &pb.GenerateTokenResp{
		AccessToken: accessToken,
		ExpiresIn:   accessExpire,
	}, nil
}

func (l *GenerateTokenLogic) getJwtToken(secretKey string, iat, seconds int64, userId int64, userChannel int64, appVer int64, authKey string, authType int64) (string, error) {
	cl := make(map[string]interface{}, 0)
	cl[ctxdata.CtxKeyJwtUserId] = userId
	cl[ctxdata.CtxKeyJwtUserChannel] = userChannel
	cl[ctxdata.CtxKeyJwtAppVer] = appVer
	cl[ctxdata.CtxKeyJwtAuthKey] = authKey
	cl[ctxdata.CtxKeyJwtAuthType] = authType

	return auth.GetJwtToken(secretKey, iat, seconds, cl)
}
